package com.shengruan.common;

import java.io.File;
import java.io.FileOutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.shengruan.admin.vo.Article;
import com.shengruan.framework.util.AuthFactory;

public class Function {

	public static String getSecMobile(String mobile)
	{
		if(mobile==null||"".equals(mobile)||mobile.length()!=11)
		{
			return mobile;
		}
		else
		{
			mobile = mobile.substring(0,3)+"****"+mobile.substring(7,11);
		}
		return mobile;
	}

	/**
	 * 计算百分比
	 * @param one
	 * @param two
	 * @return
	 */
	public static String getPercent(int one,int two)
	{

		if(two==0)
			return "0.00%";
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		df.setMinimumFractionDigits(2);
		
		String okPercent = df.format((float) one
					/ (float) two * 100)
					;
		return okPercent+"%";
	}
	public static String replaceBr(String str) {

		if (str == null || "".equals(str))
			return "";
		str = str.replaceAll("\n", "<BR/>").replaceAll("\r", "<BR/>").replaceAll(
				"\'", "&#039;");

		return str;
	}
	/**
	 * 去掉HTML标签
	 */
	public static String removeHTML(String str)
	{
		if(str ==null ||"".equals(str))
			return "";
		str = str.replaceAll("<(.*?)>", ""); //去掉HTML标签 
		str= str.replaceAll(" +", "").replace("&nbsp;", ""); //去掉所有的空格 
		return str;
	}
	/***
	 * 获得IP地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	
	public static String getCDATA(String str)
	{
		return "<![CDATA["+str+"]]>";
	}
    
	 /**
	  * 获得文件大小
	  * @param filesize
	  * @return
	  */
	 public static String getFileSize(double filesize)
	 {
		 DecimalFormat df = new DecimalFormat();
			df.setMaximumFractionDigits(1);
			df.setMinimumFractionDigits(1);
		 double sizeB = filesize;
		 double sizeM = (sizeB/(1024*1024));
		 double sizeK= sizeB/1024;
		 if(sizeM>=1)
		 {
			 
			 return  df.format(sizeM)+"M";
		 }
		 else
		 {
			 if(sizeK>=1)
			 {
				 return df.format(sizeK)+"KB";
			 }
			 else
			 {
				 return 1+"KB";
			 }
		 }
	 }
  

	public static String getAddressByIp(String ip)
	{

		IPSeeker ipSeeker = IPSeeker.getInstance();
        String source = ipSeeker.getAddress(ip);
        if(source==null||source.equals(""))
        	source = "未知";
        return source;
	}
	
	public static String turnHTML(String str)
	{
		if(str==null||"".equals(str))
			return "";
		str = str.replaceAll("<", "&lt;").replaceAll(">", "&gt;").replace("&nbsp;", "&#160;");
		
		return str;
	}
	/**Html标签转义**/
	public static String asHTML(String text) {
		if (text == null)
			return "";
		StringBuffer results = null;
		char[] orig = null;
		int beg = 0, len = text.length();
		for (int i = 0; i < len; ++i) {
			char c = text.charAt(i);
			switch (c) {
			case 0:
			case '&':
			case '<':
			case '>':
			case '"':
				if (results == null) {
					orig = text.toCharArray();
					results = new StringBuffer(len + 10);
				}
				if (i > beg)
					results.append(orig, beg, i - beg);
				beg = i + 1;
				switch (c) {
				default: // case 0:
					continue;
				case '&':
					results.append("&");
					break;
				case '<':
					results.append("<");
					break;
				case '>':
					results.append(">");
					break;
				case '"':
					results.append("");
					break;
				}
				break;
			}
		}
		if (results == null)
			return text;
		results.append(orig, beg, len - beg);
		return results.toString();
	}

	//获得当前日期
	public static String getDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date());
	}

	public static String getDetailDate() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date());
	}

	public static String getTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(new Date());
	}

	public static String getDetailDate(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(new Date(time));
	}

	public static Date getDateType(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(time);
		} catch (Exception ex) {
			return new Date();
		}
	}

	public static String getCreateTime(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		return sdf.format(new Date(time));
	}

	public static long getLongDate(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(time).getTime();
		} catch (Exception ex) {
			return 0;
		}
	}

	public static long getLongHour(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		try {
			return sdf.parse(time).getTime();
		} catch (Exception ex) {
			return 0;
		}
	}
	public static String getLDate(long time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(time));
	}
	public static long getLongTime(String time) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return sdf.parse(time).getTime();
		} catch (Exception ex) {
			return 0;
		}
	}


    /**
     * 页面日期格式化显示
     * @param time
     * @return
     */
    public static String format(String time) {
        if(StringUtils.isEmpty(time))
            return "";
        else
            return DateFormatUtils.format(Long.valueOf(time), "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * 页面密码转换
     * @param password
     * @return
     */
    public static String decryptPassword(String password) {
        if(StringUtils.isEmpty(password)){
            return "";
        }else{
            AuthFactory.passwordKey = Constants.passwordKey;
            return AuthFactory.decryptPassword(password);
        }
    }

    /**
     *
     * @return
     */
    public static List<Article> getArticleList() {
        return Constants.articleList;
    }

    public static String getDelayDays()
    {
    	return Constants.PRODUCT_DISABLE_DAYS+"";
    }

	public static String getLastDate()
	{
		long times = System.currentTimeMillis();
		long lastTimes = times-1000*60*60*24;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(new Date(lastTimes));
		
	}
	public static String getPicName() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return sdf.format(new Date());
	}
	/*
	 * 获得下一天的日期
	 */
	public static String getNextDate(String date) {
		long nTime = getLongTime(date) + 1000 * 60 * 60 * 24;
		return getLDate(nTime);
	}
	public String trans(String str) {
		if (str == null) {
			return "&nbsp;";
		} else {
			try {
				return new String(str.getBytes("ISO-8859-1"));
			} catch (Exception ex) {
				return "";
			}
		}
	}

	public static boolean createFolder(String folderPath) {
		File file = new File(folderPath);
		if (file.isDirectory() && file.exists()) {
			return false;
		} else {
			file.mkdirs();
		}
		return true;
	}

	public static void insertLog(String message) {
		File file = new File("D:\\log.txt");
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(message.getBytes());
			fos.close();
		} catch (Exception ex) {
			try {
				fos.close();
			} catch (Exception e) {

			}
		}
	}

	//更具毫秒计算总时间
	public static String getTotalTime(long time) {
		long min = time / (1000 * 60);
		long h = (min / 60);
		long m = min % 60;
		if (h > 0)
		{
			long d = h/24;
			h = h%24;
			if(d>0)
			{
				return d+"天"+h+"小时";
			}
			else
				return h + "小时" + m + "分钟";
		}
		else
			return m + "分钟";
	}
	//更具毫秒计算总时间
	  public static String getTheTotalTime(long time)
	  {
		  long min = time/(1000*60);
			long h = (min/60);
			long d = h/24;
			if(d<1)
			{
				return h+"小时";
			}
			else
			{
				min = (time-d*24*60*60*1000)/(1000*60);
				h = (min/60);
				if(h==0)
					return d+"天";
				else
					return d+"天"+h+"小时";
			}
				
	  }
	public static String getSecAndMis(long time)
	{
		long m = time/1000;
		long min = m/60;
		long mm = m%60;
		if(min>0)
			return min+"分"+mm+"秒";
		else
			return mm+"秒";
	}
	
}
